package com.yand.disk.demo.service.impl;

import com.yand.disk.demo.entity.FileInfoBean;
import com.yand.disk.demo.entity.TDownLink;
import com.yand.disk.demo.service.CheckService;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;


/**
 * @author  yanzz
 *    文件检查校验超类
 *
 */
@Service
public abstract class CheckServiceSuperImpl implements CheckService {



    /**
     * 检查文件
     *  1，检查文件是否失效
     * @param fileInfoBean
     * @return true 失效  false 未失效
     */
    public abstract boolean checkFileIsexpire(TDownLink fileInfoBean);


    /**
     * 检查下载次数
     * @param fileInfoBean
     * @return true 可下载 false 不可下载
     */
    public abstract boolean checkDownLoadCount(TDownLink fileInfoBean);


    /**
     * 检查文件是否需要验证码
     * @param fileInfoBean
     * @return true 需要 false  不需要
     */
    public abstract boolean checkFileIsValiCode(TDownLink fileInfoBean);




    @Override
    public int check(TDownLink link,HttpServletRequest request) {


        boolean isExpire = checkFileIsexpire(link);
        if(isExpire){
            return 0;
        }
        boolean isDownCount = checkDownLoadCount(link);
        if(!isDownCount){
            return 1;
        }

        //检查是否需要输入提取码
        boolean isValiCode = checkFileIsValiCode(link);

        //如果需要提取码且为GET请求返回输入提取码页面
        if(isValiCode && isGet(request)){
            return 2;
        }
        //如果需要提取码且为POST请求则校验传输过来的提取码是否正确，如果不正确则作为非法请求处理
        if(isValiCode && isPOST(request)){
            String code = link.getIdentifyingcode()+"";
            String authcode = request.getParameter("authcode");
            if(!code.equals(authcode)){
                return 4;
            }
        }
        return 3;

    }



    private boolean isGet(HttpServletRequest request){
        String type = request.getMethod();
        return "GET".equals(type);
    }

    private boolean isPOST(HttpServletRequest request){
        String type = request.getMethod();
        return "POST".equals(type);
    }

    //校验输入的参数是否一样


}
